package mobi.greenplate.client.connect;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author dmakariev
 */
public class ServerCallBuilder implements ServerCall {

    public ServerCallBuilder(ConnectionContext connectionContext) {
        this.helper = HttpClientHelper.connect(connectionContext);
    }

    private final HttpClientHelper helper;
    private String url = "";
    private Map<String, String> params = new HashMap<String, String>();
    private String stringEntity = "";

    private void clearBuilderState() {
        url = "";
        params.clear();
        stringEntity = "";
    }

    public ServerCall url(String url) {
        this.url = url;
        return this;
    }

    public ServerCall addParam(String name, String value) {
        params.put(name, value);
        return this;
    }

    public ServerCall stringEntity(String string) {
        this.stringEntity = string;
        return this;
    }

    public int get(ResponseHandler handler) {
        final int statusCode = getHelper().executeGet(getHelperContext(handler));
        clearBuilderState();
        return statusCode;
    }

    public int post(ResponseHandler handler) {
        final int statusCode = getHelper().executePost(getHelperContext(handler));
        clearBuilderState();
        return statusCode;
    }

    public int put(ResponseHandler handler) {
        final int statusCode = getHelper().executePut(getHelperContext(handler));
        clearBuilderState();
        return statusCode;
    }

    public int delete(ResponseHandler handler) {
        final int statusCode = getHelper().executeDelete(getHelperContext(handler));
        clearBuilderState();
        return statusCode;
    }

    private HttpClientHelper getHelper() {       
        return helper;
    }

    private HttpClientTemplateContext getHelperContext(ResponseHandler handler){
        return HttpClientTemplateContext.createContext(url, params, stringEntity, handler);
    }
}
